<?php
/**
 * @file
 */
function ffs_entity_admin_settings($form, &$form_state) {
  $entities = entity_get_info();
  $options = array();
  $form['ffs_list_entities'] = array('#tree' => TRUE,);
  $ffs_entity = variable_get('ffs_list_entities', NULL);
  $weight = 0;
  foreach ($entities as $entity_type => $entity) {
    if (!isset($entity['module'])) {
      continue;
    }
    if ($entity['module'] == 'eck' && !empty($entity['bundles'])) {
      foreach ($entity['bundles'] as $bundle_key => $bundle) {
        $form['ffs_list_entities'][$bundle_key] = array(
          'label' => array('#markup' => $bundle['label']),
          'weight' => array(
            '#type' => 'weight',
            '#title' => t('Weight for @title', array('@title' => $bundle['label'])),
            '#title_display' => 'invisible',
            '#default_value' => !empty($ffs_entity[$bundle_key]['weight']) ? $ffs_entity[$bundle_key]['weight'] : $weight++,
          ),
          'menu' => array(
            '#type' => 'checkbox',
            '#default_value' => !empty($ffs_entity[$bundle_key]['menu']) ? $ffs_entity[$bundle_key]['menu'] : FALSE
          ),
          'name' => array(
            '#type' => 'value',
            '#value' => $bundle['label']
          ),
          'entity_type' => array(
            '#type' => 'value',
            '#value' => $entity_type
          )
        );
      }
    }
  }

  $form['#theme'] = 'ffs_entity_admin_settings';
  return system_settings_form($form);
}

/**
 * Returns HTML for the text format administration overview form.
 *
 * @param $variables
 *   An associative array containing:
 *   - form: A render element representing the form.
 *
 * @ingroup themeable
 */
function theme_ffs_entity_admin_settings($variables) {
  $form = $variables['form'];

  $rows = array();
  foreach (element_children($form['ffs_list_entities']) as $id) {
    $form['ffs_list_entities'][$id]['weight']['#attributes']['class'] = array('text-format-order-weight');
    $rows[] = array(
      'data' => array(
        drupal_render($form['ffs_list_entities'][$id]['label']),
        drupal_render($form['ffs_list_entities'][$id]['weight']),
        drupal_render($form['ffs_list_entities'][$id]['menu']),
      ),
      'class' => array('draggable'),
    );
  }
  $header = array(t('Name'), t('Weight'), t('Active Menu'));
  $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'text-format-order')));
  $output .= drupal_render_children($form);

  drupal_add_tabledrag('text-format-order', 'order', 'sibling', 'text-format-order-weight');

  return $output;
}
